<?php

namespace App\Http\Middleware;

use App\Exceptions\ParamsException;
use App\Http\ApiConfig;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ParamsValid
{
    public function handle(Request $request, Closure $next)
    {
        $params = $request->input();
        
        $validate = Validator::make(json_decode(json_encode($params), true), ApiConfig::$reqHeadRules);
        if ($validate->fails()) {
           throw new ParamsException($validate->errors()->first());
        }
        $head = $params['head'];
        $validate = Validator::make($params['data'], ApiConfig::$config[$head['bizcode']][$head['funcode']]['validate']);
        if ($validate->fails()) {
           throw new ParamsException($validate->errors()->first());
        }

        return $next($request);
    }
}
